import ImageCompressor from 'js-image-compressor';
import { useOssToken } from '@/composables/useOssToken';
import dayjs from 'dayjs';
import { showToast } from 'vant';

const { client } = useOssToken();
/**
 * 压缩图片
 * @param file
 * @returns
 */
const compressionImage = (file: File) => {
  return new Promise<File>((resolve, reject) => {
    new ImageCompressor({
      file: file,
      quality: 0.9, // 压缩比

      // 压缩前回调
      beforeCompress: function (result: File) {
        console.log('压缩之前图片尺寸大小: ', result.size);
        console.log('mime 类型: ', result.type);
      },

      success: function (result: File) {
        console.log('压缩之后图片尺寸大小: ', result.size);
        console.log('mime 类型: ', result.type);
        console.log('实际压缩率： ', (((file.size - result.size) / file.size) * 100).toFixed(2) + '%');
        resolve(result);
      },
      error(e: any) {
        reject(e);
      },
    });
  });
};

//获取文件后缀
export const getFileSuffix = (fileName: string) => {
  const name = fileName.lastIndexOf('.'); //取到文件名开始到最后一个点的长度
  const length = fileName.length;
  return fileName.substring(name, length);
};

//文件的上传地址
export const getFilePath = (orangeName: string, type = 'images') => {
  const fileName = getFileNumber() + getFileSuffix(orangeName);
  const time = dayjs().format('YYYYMMDD');
  const result = `${type}/upload/jyWeb/${time}/${fileName}`;
  return result;
};

//oss文件名获取随机
export const getFileNumber = () => {
  const timeNumber = new Date().getTime();
  const randomNumber = Math.floor(Math.random() * 999999);
  return timeNumber + '' + randomNumber;
};

interface ResType {
  data: {
    fileName: string;
    url: string;
  };
}

/**
 * 上传图片
 * @param file 待处理文件
 * @param compression 是否压缩 默认false
 * @returns
 */
const uploadImage = async (file: File, compression = false) => {
  try {
    if (!client.value) {
      showToast('获取OSSTOKEN失败');
      return;
    }
    const filePath = getFilePath(file.name);
    let fileRes = file;
    if (compression && /^image\/*/.test(file.type)) {
      fileRes = await compressionImage(file);
    }
    const clientResult = await client.value.put(filePath, fileRes, {});
    const result: ResType = {
      data: {
        fileName: clientResult.name,
        url: clientResult.url,
      },
    };
    return Promise.resolve(result);
  } catch (e) {
    console.log('err: ', e);
    return Promise.reject(e);
  }
};

export default uploadImage;
